document.addEventListener('DOMContentLoaded', () => {
    // 侧边栏切换模块
    const sidebarMenu = document.querySelector('.sidebar-menu');
    const moduleSections = document.querySelectorAll('.module-section');

    sidebarMenu.addEventListener('click', function(e) {
        if (e.target.tagName === 'LI') {
            // 切换高亮
            sidebarMenu.querySelectorAll('li').forEach(li => li.classList.remove('active'));
            e.target.classList.add('active');
            // 切换内容
            const sectionId = e.target.getAttribute('data-section');
            moduleSections.forEach(sec => {
                if (sec.id === sectionId) {
                    sec.classList.add('active');
                } else {
                    sec.classList.remove('active');
                }
            });
        }
    });

    // 默认显示学生信息管理
    document.querySelector('.sidebar-menu li[data-section="student-info"]').classList.add('active');
    document.getElementById('student-info').classList.add('active');
    // 其余模块隐藏
    moduleSections.forEach(sec => {
        if (sec.id !== 'student-info') sec.classList.remove('active');
    });
    // ================ 数据存储 ================
    let students = JSON.parse(localStorage.getItem('students')) || [];
    let courses = JSON.parse(localStorage.getItem('courses')) || [];
    let grades = JSON.parse(localStorage.getItem('grades')) || [];
    let teachers = JSON.parse(localStorage.getItem('teachers')) || [];
    let currentEditStudentId = null;
    let currentEditCourseId = null;
    let currentEditUserId = null;

// ================ 登录/权限系统 ================
    const loginPage = document.getElementById('login-page');
    const mainPage = document.getElementById('main-page');
    const loginForm = document.getElementById('login-form');
    const logoutBtn = document.getElementById('logout-btn');


    let currentUser = null;

// 用户权限配置
    const userPermissions = {
        student: ['grade-query', 'statistics'],
        teacher: ['grade-entry', 'grade-query',  'statistics'],
        admin: ['grade-entry', 'grade-query', 'student-info', 'teacher-info', 'statistics', 'course-info'],
        superadmin: ['grade-entry', 'grade-query', 'student-info', 'teacher-info', 'statistics', 'course-info', 'user-info'] // 新增超级管理员

    };

// 登录处理
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        try {
            // 2. 添加超级管理员特殊处理
            if (username === 'superadmin' && password === '123456') {
                // 直接创建超级管理员用户
                currentUser = {
                    id: 0,
                    username: 'superadmin',
                    role: 'superadmin'
                };

                // 更新界面
                loginPage.classList.add('hidden');
                mainPage.style.display = 'flex';
                resetNavigation();
                applyPermissions();
                activateFirstAllowedSection();
                return;
            }

            // 原有登录逻辑
            const response = await fetch('/api/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ username, password })
            });

            const data = await response.json();
            if (!response.ok) throw new Error(data.message || '登录失败');

            // 设置当前用户
            currentUser = {
                id: data.user.id,
                username: data.user.username,
                role: data.user.role.toLowerCase()
            };

            // 更新界面
            loginPage.classList.add('hidden');
            mainPage.style.display = 'flex';
            resetNavigation();
            applyPermissions();
            activateFirstAllowedSection();

        } catch (error) {
            alert(error.message || '登录异常，请检查网络');
            loginForm.reset();
        }
    });

// 核心修复：权限应用（不改变显示逻辑）
    function applyPermissions() {
        const allSections = document.querySelectorAll('.module-section');
        const allMenuItems = document.querySelectorAll('.sidebar-menu li');
        const allowedSections = userPermissions[currentUser.role] || [];

        // 1. 处理模块显示权限
        allSections.forEach(section => {
            const isAllowed = allowedSections.includes(section.id);

            // 只设置data-allowed属性，不改变显示状态
            section.dataset.allowed = isAllowed;

            // 隐藏未授权模块（但保持原始.active控制）
            if (!isAllowed) {
                section.style.display = 'none';
            } else {
                section.style.display = ''; // 重置显示状态
            }
        });

        // 2. 处理菜单项显示权限
        allMenuItems.forEach(li => {
            const sectionId = li.dataset.section;
            const isAllowed = allowedSections.includes(sectionId);

            li.dataset.allowed = isAllowed;
            li.style.display = isAllowed ? '' : 'none'; // 显示/隐藏菜单项
        });
    }

// 激活第一个授权模块
    function activateFirstAllowedSection() {
        const allowedSections = userPermissions[currentUser.role] || [];
        if (allowedSections.length > 0) {
            const firstSectionId = allowedSections[0];
            activateSection(firstSectionId);
        }
    }

// 激活指定模块（统一入口）
    function activateSection(sectionId) {
        // 验证权限
        const allowedSections = userPermissions[currentUser.role] || [];
        if (!allowedSections.includes(sectionId)) {
            alert("无权访问该模块");
            return;
        }

        // 更新菜单活动状态
        document.querySelectorAll('.sidebar-menu li').forEach(li => {
            li.classList.toggle('active', li.dataset.section === sectionId);
        });

        // 更新模块显示状态
        document.querySelectorAll('.module-section').forEach(section => {
            if (section.dataset.allowed === 'true') {
                section.classList.toggle('active', section.id === sectionId);
                section.style.display = section.id === sectionId ? 'block' : 'none';
            }
        });
    }

// 重置导航状态
    function resetNavigation() {
        // 隐藏所有模块
        document.querySelectorAll('.module-section').forEach(section => {
            section.classList.remove('active');
            section.style.display = 'none';
        });

        // 重置菜单状态
        document.querySelectorAll('.sidebar-menu li').forEach(li => {
            li.classList.remove('active');
        });
    }

// 菜单点击事件处理（修复版）
    sidebarMenu.addEventListener('click', (e) => {
        if (e.target.tagName === 'LI') {
            const sectionId = e.target.dataset.section;
            activateSection(sectionId);
        }
    });

// 退出登录
    logoutBtn.addEventListener('click', () => {
        // 1. 清空当前用户
        currentUser = null;

        // 2. 重置登录页面（使用CSS类代替内联样式）
        loginPage.classList.remove('hidden');
        loginPage.style.display = ''; // 清除内联样式

        // 3. 隐藏主页面
        mainPage.style.display = 'none';

        // 4. 重置所有界面状态
        resetNavigation();
        loginForm.reset();

        // 5. 确保页面滚动位置重置
        window.scrollTo(0, 0);
    });
    // ================ 学生管理 ================

// 获取表单、学生列表和搜索输入框的DOM元素
    const studentForm = document.getElementById('student-form'); // 学生表单
    const studentList = document.getElementById('student-list'); // 学生列表容器
    const studentSearch = document.getElementById('student-search'); // 学生搜索输入框

// 初始化加载学生列表
    loadStudents();

// 异步加载学生列表的函数
    async function loadStudents() {
        try {
            // 发送GET请求获取学生列表
            const response = await fetch('http://localhost:8080/api/students');
            // 如果响应状态码不是200-299，抛出错误
            if (!response.ok) throw new Error('获取学生列表失败');
            // 解析响应数据为JSON格式
            const students = await response.json();
            // 调用渲染函数，传入学生列表数据
            renderStudentList(students); // 传递有效的数组（可能为空）
        } catch (error) {
            // 捕获错误并打印到控制台
            console.error('Error:', error);
            // 渲染空列表，避免传入undefined
            renderStudentList([]); // 传入空数组避免 undefined
            // 弹出提示框，提示用户加载失败
            alert('无法加载学生数据，请稍后重试');
        }
    }

// 监听表单的提交事件
    studentForm.addEventListener('submit', async (e) => {
        e.preventDefault(); // 阻止表单的默认提交行为

        // 获取表单中的数据
        const studentData = {
            id: document.getElementById('student-id').value.trim(), // 学号
            name: document.getElementById('student-name').value.trim(), // 姓名
            className: document.getElementById('student-class').value.trim() // 班级
        };

        // 检查表单数据是否完整
        if (!studentData.id || !studentData.name || !studentData.className) {
            alert('请填写完整信息！'); // 弹出提示框
            return; // 如果数据不完整，直接返回
        }

        try {
            let response; // 定义响应变量
            if (currentEditStudentId) {
                // 如果当前处于编辑模式，发送PUT请求更新学生信息
                response = await fetch(`http://localhost:8080/api/students/${currentEditStudentId}`, {
                    method: 'PUT', // 请求方法为PUT
                    headers: { 'Content-Type': 'application/json' }, // 设置请求头
                    body: JSON.stringify(studentData) // 将表单数据转换为JSON字符串
                });
            } else {
                // 如果当前处于新增模式，发送POST请求添加学生
                response = await fetch('http://localhost:8080/api/students', {
                    method: 'POST', // 请求方法为POST
                    headers: { 'Content-Type': 'application/json' }, // 设置请求头
                    body: JSON.stringify(studentData) // 将表单数据转换为JSON字符串
                });
            }

            // 如果响应状态码不是200-299，抛出错误
            if (!response.ok) {
                const errorData = await response.json(); // 解析错误信息
                throw new Error(errorData.message || '操作失败'); // 抛出错误
            }

            resetStudentForm(); // 重置表单
            await loadStudents(); // 刷新学生列表
            alert(currentEditStudentId ? '修改成功！' : '添加成功！'); // 弹出成功提示
        } catch (error) {
            console.error('Error:', error); // 捕获错误并打印到控制台
            alert(`操作失败: ${error.message}`); // 弹出错误提示
        }
    });


    // 新增搜索函数
    window.searchStudents = async function() {
        const keyword = studentSearch.value.trim();
        try {
            const response = await fetch(`http://localhost:8080/api/students/search?keyword=${encodeURIComponent(keyword)}`);
            if (!response.ok) throw new Error('搜索失败');
            const students = await response.json();
            renderStudentList(students);
        } catch (error) {
            console.error('搜索错误:', error);
            alert('搜索失败: ' + error.message);
        }
    };

// 渲染学生列表的函数
    function renderStudentList(students = [], filter = '') {

        studentList.innerHTML = students.map(s => `
        <div class="list-item">
            <span>学号：${s.id}</span> <!-- 显示学号 -->
            <span>姓名：${s.name}</span> <!-- 显示姓名 -->
            <span>班级：${s.className}</span> <!-- 显示班级 -->
            <button onclick="editStudent('${s.id}')">编辑</button> <!-- 编辑按钮 -->
            <button onclick="deleteStudent('${s.id}')">删除</button> <!-- 删除按钮 -->
        </div>
    `).join(''); // 将数组转换为字符串
    }

// 编辑学生信息的函数
    window.editStudent = async (id) => {
        try {
            // 发送GET请求，获取指定ID的学生信息
            const response = await fetch(`http://localhost:8080/api/students/${id}`);
            // 如果响应状态码不是200-299，抛出错误
            if (!response.ok) throw new Error('获取学生信息失败');
            // 解析响应数据为JSON格式
            const student = await response.json();

            // 将学生信息填充到表单中
            document.getElementById('student-id').value = student.id; // 学号
            document.getElementById('student-name').value = student.name; // 姓名
            document.getElementById('student-class').value = student.className; // 班级
            currentEditStudentId = student.id; // 设置当前编辑的学生ID
            toggleEditMode(true); // 切换到编辑模式
        } catch (error) {
            console.error('Error:', error); // 捕获错误并打印到控制台
            alert('无法获取学生信息'); // 弹出错误提示
        }
    };

// 删除学生信息的函数
    window.deleteStudent = async (id) => {
        // 弹出确认框，确认是否删除
        if (!confirm('确定要删除该学生吗？')) return;

        try {
            // 发送DELETE请求，删除指定ID的学生
            const response = await fetch(`http://localhost:8080/api/students/${id}`, {
                method: 'DELETE' // 请求方法为DELETE
            });

            // 如果响应状态码不是200-299，抛出错误
            if (!response.ok) throw new Error('删除失败');
            await loadStudents(); // 刷新学生列表
            alert('删除成功！'); // 弹出成功提示
        } catch (error) {
            console.error('Error:', error); // 捕获错误并打印到控制台
            alert('删除操作失败'); // 弹出错误提示
        }
    };

// 取消编辑的函数
    window.cancelEditStudent = () => {
        resetStudentForm(); // 重置表单
        toggleEditMode(false); // 退出编辑模式
    };

// 重置表单的函数
    function resetStudentForm() {
        studentForm.reset(); // 重置表单内容
        currentEditStudentId = null; // 清空当前编辑的学生ID
    }

// 切换编辑模式的函数
    function toggleEditMode(isEditing) {
        // 根据是否处于编辑模式，切换按钮的显示状态
        document.getElementById('student-submit-btn').style.display = isEditing ? 'none' : 'inline-block'; // 提交按钮
        document.getElementById('student-update-btn').style.display = isEditing ? 'inline-block' : 'none'; // 更新按钮
    }

// ================ 教师管理 ================
    const teacherForm = document.getElementById('teacher-form');
    const teacherList = document.getElementById('teacher-list');
    const teacherSearch = document.getElementById('teacher-search');
    let currentEditTeacherId = null;

// 初始化加载教师列表
    loadTeachers();

    async function loadTeachers() {
        try {
            const response = await fetch('http://localhost:8080/api/teachers');
            if (!response.ok) throw new Error('获取教师列表失败');
            const teachers = await response.json();
            renderTeacherList(teachers);
        } catch (error) {
            console.error('Error:', error);
            renderTeacherList([]);
            alert('无法加载教师数据，请稍后重试');
        }
    }

    teacherForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const teacherData = {
            id: document.getElementById('teacher-id').value.trim(),
            name: document.getElementById('teacher-name').value.trim()
        };

        if (!teacherData.id || !teacherData.name) {
            alert('请填写完整信息！');
            return;
        }

        try {
            let response;
            if (currentEditTeacherId) {
                response = await fetch(`http://localhost:8080/api/teachers/${currentEditTeacherId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(teacherData)
                });
            } else {
                response = await fetch('http://localhost:8080/api/teachers', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(teacherData)
                });
            }

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '操作失败');
            }

            resetTeacherForm();
            await loadTeachers();
            alert(currentEditTeacherId ? '修改成功！' : '添加成功！');
        } catch (error) {
            console.error('Error:', error);
            alert(`操作失败: ${error.message}`);
        }
    });

    window.searchTeachers = async function() {
        const keyword = teacherSearch.value.trim();
        try {
            const response = await fetch(`http://localhost:8080/api/teachers/search?keyword=${encodeURIComponent(keyword)}`);
            if (!response.ok) throw new Error('搜索失败');
            const teachers = await response.json();
            renderTeacherList(teachers);
        } catch (error) {
            console.error('搜索错误:', error);
            alert('搜索失败: ' + error.message);
        }
    };

    function renderTeacherList(teachers = []) {
        teacherList.innerHTML = teachers.map(t => `
        <div class="list-item">
            <span>编号：${t.id}</span>
            <span>姓名：${t.name}</span>
            <button onclick="editTeacher('${t.id}')">编辑</button>
            <button onclick="deleteTeacher('${t.id}')">删除</button>
        </div>
    `).join('');
    }

    window.editTeacher = async (id) => {
        try {
            const response = await fetch(`http://localhost:8080/api/teachers/${id}`);
            if (!response.ok) throw new Error('获取教师信息失败');
            const teacher = await response.json();

            document.getElementById('teacher-id').value = teacher.id;
            document.getElementById('teacher-name').value = teacher.name;
            currentEditTeacherId = teacher.id;
            toggleTeacherEditMode(true);
        } catch (error) {
            console.error('Error:', error);
            alert('无法获取教师信息');
        }
    };

    window.deleteTeacher = async (id) => {
        if (!confirm('确定要删除该教师吗？')) return;

        try {
            const response = await fetch(`http://localhost:8080/api/teachers/${id}`, {
                method: 'DELETE'
            });

            if (!response.ok) throw new Error('删除失败');
            await loadTeachers();
            alert('删除成功！');
        } catch (error) {
            console.error('Error:', error);
            alert('删除操作失败');
        }
    };

    window.cancelEditTeacher = () => {
        resetTeacherForm();
        toggleTeacherEditMode(false);
    };

    function resetTeacherForm() {
        teacherForm.reset();
        currentEditTeacherId = null;
    }

    function toggleTeacherEditMode(isEditing) {
        document.getElementById('teacher-submit-btn').style.display = isEditing ? 'none' : 'inline-block';
        document.getElementById('teacher-update-btn').style.display = isEditing ? 'inline-block' : 'none';
    }

// ================ 课程管理 ================
    const courseForm = document.getElementById('course-form');
    const courseList = document.getElementById('course-list');
    const courseSearch = document.getElementById('course-search');


    async function loadCourses() {
        try {
            const response = await fetch('http://localhost:8080/api/courses');
            const courses = await response.json();
            renderCourseList(courses);
        } catch (error) {
            console.error('加载课程失败:', error);
            alert('无法加载课程数据');
        }
    }

    function renderCourseList(courses, filter = '') {
        const filteredCourses = courses.filter(c =>
            c.courseId.includes(filter) || c.courseName.includes(filter)
        );
        courseList.innerHTML = filteredCourses.map(c => `
        <div class="list-item">
            <span>课程编号：${c.courseId}</span>
            <span>课程名称：${c.courseName}</span>
            <span>学分：${c.credit}</span>
            <span>授课教师：${c.teacher}</span>
            <button onclick="editCourse('${c.courseId}')">编辑</button>
            <button onclick="deleteCourse('${c.courseId}')">删除</button>
        </div>
    `).join('');
    }

    courseForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const courseData = {
            courseId: document.getElementById('course-id').value.trim(),
            courseName: document.getElementById('course-name').value.trim(),
            credit: parseInt(document.getElementById('credit').value),
            teacher: document.getElementById('teacher').value.trim()
        };

        try {
            let response;
            if (currentEditCourseId) {
                response = await fetch(`http://localhost:8080/api/courses/${currentEditCourseId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(courseData)
                });
            } else {
                response = await fetch('http://localhost:8080/api/courses', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(courseData)
                });
            }

            if (!response.ok) throw new Error('操作失败');
            await loadCourses();
            resetCourseForm();
            alert(currentEditCourseId ? '修改成功！' : '添加成功！');
        } catch (error) {
            console.error('错误:', error);
            alert('操作失败: ' + error.message);
        }
    });

    let originalCourseId = null;

/// 进入编辑模式
    window.editCourse = async (courseId) => {

        try {
            const response = await fetch(`http://localhost:8080/api/courses/${courseId}`);
            if (!response.ok) throw new Error("请求失败");
            const course = await response.json();
            // 填充表单
            document.getElementById('course-id').value = course.courseId;
            document.getElementById('course-name').value = course.courseName;
            document.getElementById('credit').value = course.credit;
            document.getElementById('teacher').value = course.teacher;
            currentEditCourseId = course.courseId;
            // 切换按钮状态
            document.getElementById('course-submit-btn').style.display = 'none';
            document.getElementById('course-update-btn').style.display = 'block';
        } catch (error) {
            alert("加载课程失败：" + error.message);
        }
        let originalCourseId=currentEditStudentId;//保留原始课程编号
        fetch(`http://localhost:8080/api/courses/${originalCourseId}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                courseId: document.getElementById('course-id').value.trim(),
                courseName: document.getElementById('course-name').value.trim(),
                credit: parseInt(document.getElementById('credit').value),
                teacher: document.getElementById('teacher').value.trim()
            })
        });
    };

// 提交修改
    document.getElementById('course-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        const courseData = {
            courseId: document.getElementById('course-id').value.trim(),
            courseName: document.getElementById('course-name').value.trim(),
            credit: parseInt(document.getElementById('credit').value),
            teacher: document.getElementById('teacher').value.trim()
        };


    });


    window.deleteCourse = async (courseId) => {
        if (!confirm('确定要删除该课程吗？')) return;
        try {
            await fetch(`http://localhost:8080/api/courses/${courseId}`, { method: 'DELETE' });
            await loadCourses();
            alert('删除成功！');
        } catch (error) {
            console.error('删除失败:', error);
        }
    };

    window.cancelEditCourse = function() {
        resetCourseForm();
        toggleCourseEditMode(false);
    };
    window.searchCourses = async function() {
        const keyword = document.getElementById('course-search').value.trim();
        try {
            const response = await fetch(`http://localhost:8080/api/courses/search?keyword=${encodeURIComponent(keyword)}`);
            if (!response.ok) throw new Error('搜索失败');
            const courses = await response.json();
            renderCourseList(courses);
        } catch (error) {
            console.error('搜索错误:', error);
            alert('搜索失败: ' + error.message);
        }
    };

    function resetCourseForm() {
        courseForm.reset();
        currentEditCourseId = null;
        toggleCourseEditMode(false);
    }

    function toggleCourseEditMode(isEditing) {
        document.getElementById('course-submit-btn').style.display = isEditing ? 'none' : 'block';
        document.getElementById('course-update-btn').style.display = isEditing ? 'block' : 'none';
    }

// 初始化加载课程列表
    loadCourses();

    // ================用户信息模块 ================
    // 获取用户表单、用户列表和搜索输入框的DOM元素
    const userForm = document.getElementById('user-form');
    const userList = document.getElementById('user-list');
    const userSearch = document.getElementById('user-search');

// 初始化加载用户列表
    loadUsers();

// 异步加载用户列表的函数
    async function loadUsers() {
        try {
            const response = await fetch('http://localhost:8080/api/users');
            if (!response.ok) throw new Error('获取用户列表失败');
            const users = await response.json();
            renderUserList(users);
        } catch (error) {
            console.error('Error:', error);
            renderUserList([]);
            alert('无法加载用户数据，请稍后重试');
        }
    }

// 监听表单的提交事件
    userForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const userData = {
            id: document.getElementById('user-id').value.trim(),
            username: document.getElementById('user-username').value.trim(),
            password: document.getElementById('user-password').value.trim(),
            real_name: document.getElementById('user-real_name').value.trim(),
            role: document.getElementById('user-role').value.trim()
        };

        if (!userData.id || !userData.username || !userData.password ||
            !userData.real_name || !userData.role) {
            alert('请填写完整信息！');
            return;
        }

        try {
            let response;
            if (currentEditUserId) {
                response = await fetch(`http://localhost:8080/api/users/${currentEditUserId}`, {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(userData)
                });
            } else {
                response = await fetch('http://localhost:8080/api/users', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(userData)
                });
            }

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '操作失败');
            }

            resetUserForm();
            await loadUsers();
            alert(currentEditUserId ? '修改成功！' : '添加成功！');
        } catch (error) {
            console.error('Error:', error);
            alert(`操作失败: ${error.message}`);
        }
    });

// 新增搜索函数
    window.searchUsers = async function() {
        const keyword = userSearch.value.trim();
        try {
            const response = await fetch(`http://localhost:8080/api/users/search?keyword=${encodeURIComponent(keyword)}`);
            if (!response.ok) throw new Error('搜索失败');
            const users = await response.json();
            renderUserList(users);
        } catch (error) {
            console.error('搜索错误:', error);
            alert('搜索失败: ' + error.message);
        }
    };

// 渲染用户列表的函数
    function renderUserList(users = []) {
        userList.innerHTML = users.map(u => `
        <div class="list-item">
            <span>id：${u.id}</span>
            <span>用户名：${u.username}</span>
            <span>密码：${u.password}</span>
            <span>姓名：${u.real_name}</span>
            <span>角色：${u.role}</span>
            <button onclick="editUser('${u.id}')">编辑</button>
            <button onclick="deleteUser('${u.id}')">删除</button>
        </div>
    `).join('');
    }

// 编辑用户信息的函数
    window.editUser = async (id) => {
        try {
            const response = await fetch(`http://localhost:8080/api/users/${id}`);
            if (!response.ok) throw new Error('获取用户信息失败');
            const user = await response.json();

            document.getElementById('user-id').value = user.id;
            document.getElementById('user-username').value = user.username;
            document.getElementById('user-password').value = user.password;
            document.getElementById('user-real_name').value = user.real_name;
            document.getElementById('user-role').value = user.role;
            currentEditUserId = user.id;
            toggleEditMode(true);
        } catch (error) {
            console.error('Error:', error);
            alert('无法获取用户信息');
        }
    };

// 删除用户信息的函数
    window.deleteUser = async (id) => {
        if (!confirm('确定要删除该用户吗？')) return;

        try {
            const response = await fetch(`http://localhost:8080/api/users/${id}`, {
                method: 'DELETE'
            });

            if (!response.ok) throw new Error('删除失败');
            await loadUsers();
            alert('删除成功！');
        } catch (error) {
            console.error('Error:', error);
            alert('删除操作失败');
        }
    };

// 取消编辑的函数
    window.cancelEditUser = () => {
        resetUserForm();
        toggleEditMode(false);
    };

// 重置表单的函数
    function resetUserForm() {
        userForm.reset();
        currentEditUserId = null;
    }

// 切换编辑模式的函数
    function toggleEditMode(isEditing) {
        document.getElementById('user-submit-btn').style.display = isEditing ? 'none' : 'inline-block';
        document.getElementById('user-update-btn').style.display = isEditing ? 'inline-block' : 'none';
    }



    // ================ 成绩录入 ================
    const gradeForm = document.getElementById('grade-form');
    const courseSelect = document.getElementById('course-select');
    const studentSelect = document.getElementById('student-select');

// 动态加载课程和学生选项
    async function loadCourseOptions() {
        try {
            const response = await fetch('http://localhost:8080/api/courses');
            const courses = await response.json();
            courseSelect.innerHTML = courses.map(c => `
            <option value="${c.courseId}">${c.courseName}</option>
        `).join('');
        } catch (error) {
            console.error('加载课程失败:', error);
        }
    }

    async function loadStudentOptions() {
        try {
            const response = await fetch('http://localhost:8080/api/students');
            const students = await response.json();
            studentSelect.innerHTML = students.map(s => `
            <option value="${s.id}">${s.name} (${s.id})</option>
        `).join('');
        } catch (error) {
            console.error('加载学生失败:', error);
        }
    }

    gradeForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const courseId = courseSelect.value;
        const studentId = studentSelect.value;
        const score = document.getElementById('grade').value;

        if (!courseId || !studentId || !score) {
            alert('请填写完整信息！');
            return;
        }

        try {
            const gradeData = {
                studentId: studentId,
                courseId: courseId,
                score: parseFloat(score)
            };

            const response = await fetch('http://localhost:8080/api/grades', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(gradeData)
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '操作失败');
            }

            alert('成绩录入成功！');
            gradeForm.reset();
        } catch (error) {
            console.error('Error:', error);
            alert(`操作失败: ${error.message}`);
        }
    });

// 初始化时加载选项
    async function initializeGradeEntry() {
        await loadCourseOptions();
        await loadStudentOptions();
    }
    initializeGradeEntry();

    // ================ 成绩查询 ================
    const queryForm = document.getElementById('query-form');
    const queryResult = document.getElementById('query-result');

    async function searchGrades() {
        const studentId = document.getElementById('query-student-id').value.trim();

        try {
            const response = await fetch(`http://localhost:8080/api/grades/student/${studentId}`);
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.message || '查询失败');
            }

            const grades = await response.json();
            renderGradeResult(grades);
        } catch (error) {
            console.error('查询错误:', error);
            queryResult.innerHTML = `<p class="error">${error.message}</p>`;
        }
    }

    function renderGradeResult(grades) {
        if (grades.length === 0) {
            queryResult.innerHTML = '<p>未找到相关成绩记录</p>';
            return;
        }

        const tableHtml = `
        <table class="grade-table">
            <thead>
                <tr>
                    <th>课程编号</th>
                    <th>课程名称</th>
                    <th>成绩</th>
                    <th>班级</th>
                </tr>
            </thead>
            <tbody>
                ${grades.map(g => `
                    <tr>
                        <td>${g.courseId}</td>
                        <td>${g.courseName}</td>
                        <td>${g.score.toFixed(1)}</td>
                        <td>${g.className}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
    `;

        const studentInfo = grades.length > 0 ?
            `<h3>${grades[0].studentName}（${grades[0].studentId}）成绩单</h3>` : '';

        queryResult.innerHTML = studentInfo + tableHtml;
    }

// 表单提交事件
    queryForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        await searchGrades();
    });

// 实时搜索（可选）
    document.getElementById('query-student-id').addEventListener('input', debounce(async () => {
        await searchGrades();
    }, 500));
    // ================ 初始化加载 ================
    document.addEventListener('DOMContentLoaded', async () => {
        try {
            await loadClassOptions();
            await loadCourseOptions();
            await loadStudentOptions();
        } catch (error) {
            console.error("初始化失败:", error);
        }
    });


// 初始化加载默认班级数据
    loadData();
    // ================ 初始化 ================
    function renderAllData() {
        renderStudentList();
        renderCourseList();
        loadCourseOptions();
        loadStudentOptions();
        loadClassOptions(); // 加载班级选项
        renderStatistics(); // 初始渲染图表
    }


});
// ================ 统计分析 ================
// ================ 统计分析 ================
let myChart = null;

async function loadData() {
    try {
        console.log("点击按钮触发 loadData 函数");

        // 1. 获取班级参数
        const className = document.getElementById('classSelector').value;
        console.log("选择的班级：", className);

        // 2. 获取平均分数据
        const response = await fetch(`/api/stats/class-avg?className=${encodeURIComponent(className)}`);
        console.log("平均分响应状态码：", response.status);
        if (!response.ok) throw new Error(`请求失败，状态码：${response.status}`);
        const data = await response.json();
        console.log("平均分原始数据：", data);

        // 3. 获取课程数据
        const courseResponse = await fetch('/api/courses');
        if (!courseResponse.ok) throw new Error("课程数据请求失败");
        const courses = await courseResponse.json();
        console.log("课程原始数据：", courses);

        // 4. 生成课程名称标签（关键修正）
        const labels = Object.keys(data).map(courseId => {
            // 根据课程编号查找对应课程名称
            const course = Array.isArray(courses)
                ? courses.find(c => c.courseId === courseId)
                : courses[courseId]; // 兼容对象格式
            return course?.courseName || courseId; // 保底显示编号
        });

        // 5. 提取分数值
        const values = Object.values(data);
        console.log("图表标签：", labels);
        console.log("图表数据：", values);

        // 6. 销毁旧图表
        if (myChart) myChart.destroy();

        // 7. 渲染新图表
        const ctx = document.getElementById('scoreChart').getContext('2d');
        myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: `班级 ${className} 平均分`,
                    data: values,
                    backgroundColor: 'rgba(54, 162, 235, 0.5)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100,
                        ticks: { color: '#666' }
                    },
                    x: {
                        ticks: { color: '#666' }
                    }
                }
            }
        });

    } catch (error) {
        console.error("图表生成失败：", error);
        alert(`图表生成失败：${error.message}`);
    }
}